import app from '@/App.vue'
import { baseUrl } from '@/js/config/index.js'

const navigateTo = (auth, url) => {
	if (auth) { //需要验证
		// #ifdef H5
		uni.navigateTo({
			url: uni.getStorageSync('token') == '' ? '/pages/login/login' : url
		})
		// #endif
		// #ifdef MP-WEIXIN
		uni.navigateTo({
			url: uni.getStorageSync('token') == '' ? '/pages/login/wxLogin' : url
		})
		// #endif
	} else {
		uni.navigateTo({
			url: url
		});
	}
};

// 手机号码验证
const isPhoneAvailable = function(phone) {
	var myreg = /^(1[3-9])\d{9}$/;
	return myreg.test(phone);
};

const HokdoInit = function(res) {
	console.log(res)
	// 账号已停用
	if (res.data.cin_status == '2') {
		uni.showModal({
			title: '提示',
			content: '账号已被停用，请联系平台客服启用',
			showCancel: false,
			confirmColor: '#1E74F3',
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
				}
			}
		});
	} else {
		if (!res.data.token) {
			// uni.navigateTo({
			// 	url: '/pagesA/my/info?phone=' + res.data.phone
			// })
			autoRegister(res)
			return
		}
		uni.showToast({ title: '登录成功！' })
		uni.setStorageSync('token', res.data.token)
		uni.setStorageSync('userinfo', res.data || {})
		app.globalData.userInfo = res.data || {}
		setTimeout(() => {
			uni.reLaunch({ url: '/pages/index/index' })
		}, 600)
	}
}

function autoRegister(res) {
	uni.request({
		url: baseUrl + '/login/login/reg',
		method: 'post',
		data: {
			mobile: res.data.phone
		},
		success: result => {
			console.info('result', result)
			if (result.data.code === 200) {
				let res = result.data
				HokdoInit(res)
			} else {
				uni.$u.toast(result.data.msg)
				uni.navigateTo({ url: '/pages/login/login' })
			}
		}
	})
}
export default {
	navigateTo,
	isPhoneAvailable,
	HokdoInit
};